/*
 * Tab.cpp
 *
 *  Created on: 01/05/2012
 *      Author: lucho0
 */

#include "Tab.h"

Tab::Tab(std::string label, int posX, int posY, Widget* parent) :
	Widget(posX, posY, NULL, parent) {

	std::stringstream unselectedSurfacePath;
	unselectedSurfacePath << TAB_IMAGES_DEFAULT_FOLDER << label << "/"
			<< "unselected.png";
	std::stringstream selectedSurfacePath;
	selectedSurfacePath << TAB_IMAGES_DEFAULT_FOLDER << label << "/"
			<< "selected.png";
	std::stringstream mouseOverSurfacePath;
	mouseOverSurfacePath << TAB_IMAGES_DEFAULT_FOLDER << label << "/"
			<< "mouseOver.png";

	this->unselectedSurface = SurfaceUtils::loadImage(
			unselectedSurfacePath.str());
	this->selectedSurface = SurfaceUtils::loadImage(selectedSurfacePath.str());
	this->mouseOverSurface
			= SurfaceUtils::loadImage(mouseOverSurfacePath.str());

	this->selected = false;

	this->pressed = false;
	this->mouseOver = false;
	this->clicked = false;

	this->surface = this->unselectedSurface;
}

Tab::~Tab() {
	if (selectedSurface != NULL)
		SDL_FreeSurface(this->selectedSurface);
	if (unselectedSurface != NULL)
		SDL_FreeSurface(this->unselectedSurface);
	if (mouseOverSurface != NULL)
		SDL_FreeSurface(this->mouseOverSurface);
}

void Tab::select() {
	this->selected = true;
	this->surface = this->selectedSurface;
}

void Tab::unselect() {
	this->selected = false;
	this->surface = this->unselectedSurface;
}

bool Tab::isSelected() {
	return this->selected;
}

void Tab::handleEvent(Event event) {
	this->clicked = false;
	if (event.getEvent()->type == SDL_MOUSEMOTION) {
		if (this->isMouseOver(event)) {
			this->mouseOver = true;
			this->pressed = false;
		}
	} else {
		if (event.getEvent()->type == SDL_MOUSEBUTTONDOWN) {
			if (event.getEvent()->button.button == SDL_BUTTON_LEFT) {
				if (this->isMouseOver(event)) {
					this->pressed = true;
				}
			}
		} else {
			if (event.getEvent()->type == SDL_MOUSEBUTTONUP) {
				if (event.getEvent()->button.button == SDL_BUTTON_LEFT) {
					if (this->isMouseOver(event) && this->pressed) {
						this-> clicked = true;
					}
				}

			}
			this->pressed = false;
		}
	}
}

void Tab::resolve() {
	if (this->clicked) {
		select();

	} else {
		if (!this->selected && mouseOver) {
			this->surface = this->mouseOverSurface;
		} else {
			unselect();

		}
	}

}
